package user

import (
	"encoding/json"
	"io/ioutil"
	"log"
	"src/config"
	"src/mapper"
	"src/model"
	"src/service"
	"src/utils"
)

type UserC struct {
}

var UserCI *UserC

func NewUserC() *UserC {
	return &UserC{}
}

// 注册
func (*UserC) Reg(b *service.Req) {

	// 接收post参数
	body, err := ioutil.ReadAll(b.R.Body)
	if err != nil {
		log.Println(err)
	}
	var reg model.LoginModelReg
	json.Unmarshal(body, &reg)

	if len(reg.Username) < 6 {
		b.Fail("用户名长度不能少于6位")
		return
	}
	if len(reg.Password) < 6 {
		b.Fail("密码长度不能少于6位")
		return
	}
	//loginAuthType := config.V().GetString("client.login-auth-type")

	user, _ := service.UserI.GetUser(&mapper.User{Username: reg.Username})
	if user != nil {
		b.Fail("账号已存在")
		return
	}
	Jwt, err := utils.NewJwt().SetUid(reg.Uid).SetUName(reg.Username).CreateToken()
	if err != nil {
		b.Fail(err.Error())
		return
	}
	user = new(mapper.User)
	user.Username = reg.Username
	user.Password = reg.Password
	user.Nickname = reg.Nickname
	user.Token = Jwt.Token
	err = service.UserI.AddUser(user)
	if err != nil {
		b.Fail(err.Error())
		return
	}
	b.Ok("注册成功")

}

// 已登录用户获取 用户信息
func (*UserC) GetList(b *service.Req) {
	params := b.GetParams()
	log.Println("params:", params)
	page := params["page"].(float64)
	start := int(page)
	if start <= 0 {
		start = 1
	}
	pageNum := 20

	end := pageNum * start

	//获取用户数据
	user, err := service.UserI.GetList(nil, end-pageNum, end)
	if err != nil {
		b.Fail(err.Error())
		return
	}
	b.Ok(user)
}

// 已登录用户获取 用户信息
func (*UserC) GetUserinfo(b *service.Req) {
	//获取用户数据

	user, err := service.UserI.GetUser(&mapper.User{Uid: b.User.Uid})
	if err != nil {
		b.Fail(err.Error())
		return
	}
	b.Ok(user)
}

// 用户登录
func (*UserC) Login(b *service.Req) {
	// 接收post参数

	body, err := ioutil.ReadAll(b.R.Body)
	if err != nil {
		log.Println(err)
	}
	var reg model.LoginModelReg
	json.Unmarshal(body, &reg)
	if len(reg.Username) < 6 {
		b.Fail("用户名长度不能少于6位")
		return
	}
	if len(reg.Password) < 6 {
		b.Fail("密码长度不能少于6位")
		return
	}
	loginAuthType := config.V().GetString("client.login-auth-type")

	user, err := service.UserI.GetUser(&mapper.User{Username: reg.Username})
	if user == nil {
		b.Fail("用户不存在")
		return
	}
	if err != nil {
		b.Fail("密码不正确")
		return
	}

	Jwt, err := utils.NewJwt().SetUid(user.Uid).SetUName(user.Username).CreateToken()
	if err != nil {
		b.Fail(err.Error())
		return
	}
	var auth model.TokenModel
	auth.Token = Jwt.Token
	auth.Expiry = Jwt.ExpiresAt
	//user.Token = Jwt.Token
	//var loginInfo model.LoginInfo
	//loginInfo.Token = auth
	//loginInfo.Userinfo = *user
	if loginAuthType == "mysql" {
		user.Token = Jwt.Token
		err = service.UserI.UpdateUser(user)
	}
	b.Ok(auth)

}
